/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.saving;

import java.io.Serializable;
import java.math.BigDecimal;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import src.domain.saving.Saving;
import src.domain.saving.Savtrx;
import src.domain.security.Users;
import src.domain.system.Numbering;
import src.services.CRUEDService;
import src.services.saving.SavingModel;
import src.services.saving.SavtrxModel;
import src.util.Messager;
import src.view.security.LoginBean;

/**
 *
 * @author jay
 */
@ManagedBean
@SessionScoped
public class SavtrxBean implements Serializable {
   
    private Savtrx savtrx;
    private Saving savdest;  
    private String accntDest;
    private Integer branchId, searchSatus=0; //1: saerch customer; 2: search join;
    private SavtrxModel savHelper;
    private boolean editMode = false, authorized=false, insertionMode=false;
    private CRUEDService csHelper;
    private BigDecimal balanceDest = BigDecimal.ZERO, balanceSrc = BigDecimal.ZERO;
    private Users user;
    private String defaultButton="doNothingSavtrx";
    private boolean showLookup=false, showLookupDest=false;
    
    public SavtrxBean() {
        ambilUser(); 
        this.savHelper = new SavtrxModel();
        this.csHelper = new CRUEDService();
        editMode = false;
        authorized = false;
    }
    
    private boolean cekConfig() {
        boolean complete=true;
        this.branchId = user.getBranch().getBranchId();
        
        if (this.branchId==null) complete=false;
            
        if(complete==false) Messager.showWarning("savingUnconfig");
        
        return complete;
    }

    public boolean isShowLookup() {
        return showLookup;
    }

    public void setShowLookup(boolean showLookup) {
        this.showLookup = showLookup;
    }

    public boolean isShowLookupDest() {
        return showLookupDest;
    }

    public void setShowLookupDest(boolean showLookupDest) {
        this.showLookupDest = showLookupDest;
    }
        
    public boolean isEditMode() {
        return editMode;
    }

    public boolean isAuthorized() {
        return authorized;
    }
        
    public Savtrx getSavtrx() {
        return savtrx;
    }

    public void setSavtrx(Savtrx savtrx) {
        this.savtrx = savtrx;
    }

    public Saving getSavdest() {
        return savdest;
    }
    
    public String getAccntDest() {
        return accntDest;
    }

    public void setAccntDest(String accntDest) {
        this.accntDest = accntDest;
    }

    public BigDecimal getBalanceDest() {
        return balanceDest;
    }

    public BigDecimal getBalanceSrc() {
        return balanceSrc;
    }
    
    public Integer getSearchSatus() {
        return searchSatus;
    }

    public void setSearchSatus(Integer searchSatus) {
        this.searchSatus = searchSatus;
    }
        
    public void calcSaldoAhir() {
        if (savtrx.getAmount() != null) {
            this.balanceSrc = savtrx.getSaving().getBalance().subtract(savtrx.getAmount());
            this.balanceDest = savdest.getBalance().add(savtrx.getAmount());
        }    
    }
    
    public Saving getSavingByAccount(String accntNo) {
        SavingModel helper = new SavingModel();
        Saving saving = helper.getByAccount(accntNo);
        return saving;
    }
    
    public void getSavingSrc(String norek) {
        boolean found = false;       
        if ("null".equals(norek)) norek = savtrx.getSaving().getAccountNo();
        
        if (norek!=null ) {
            Saving saving = getSavingByAccount(norek);
            if (saving==null) {
                //reset
                this.savtrx.setSaving(new Saving());
                Messager.showWarning("accntNotFound");
            }
            
            else {
                found=true;
                defaultButton="doNothingSavtrx";
                this.savtrx.setSaving(saving);
            }
        }
        RequestContext.getCurrentInstance().addCallbackParam("success", found);
    }
    
    public void getSavingDest(String norek) {
        boolean found = false;
        if ("null".equals(norek)) norek = accntDest;
        if (norek!=null ) {
            
            savdest = getSavingByAccount(norek);
            if (savdest==null) {
                
                this.accntDest = "";
                this.savtrx.setDestSavaccntId(0);
                savdest = new Saving();
                
                Messager.showWarning("accntNotFound");
            
            }else{
                found=true;
                defaultButton="doNothingSavtrx";
                this.accntDest = savdest.getAccountNo();
                this.savtrx.setDestSavaccntId(savdest.getSavaccntId());
            }
        }
        RequestContext.getCurrentInstance().addCallbackParam("success", found);
    }
    
    private void initForm() {
        this.editMode = true;
        this.authorized = true;
        this.savdest = new Saving();
        this.accntDest="";
        showLookup=false;
        showLookupDest=false;
        defaultButton="doNothingSavtrx";
        balanceDest = BigDecimal.ZERO;
        balanceSrc = BigDecimal.ZERO;
    }
        
    private void newNumber() {
                
        if (savtrx.getBranchId() != null) {
            Numbering currentNo = csHelper.getNextTrxNumber(2, savtrx.getBranchId(), 0, 1);
            savtrx.setTransferNo(currentNo.getTrxNum());
            //Numbering currentNo
        }
        //return currentNo;
    }
    
    public final void newData() {  
        initForm();
        cekConfig();
        if (this.savtrx!=null) savtrx = null;
        this.savtrx = new Savtrx();
        this.savtrx.setBranchId(branchId);
        insertionMode = true;
    }
        
    public boolean validate() {
        
        boolean hasil=true;
        
        BigDecimal balance = savtrx.getSaving().getBalance();
        BigDecimal transferAmount = savtrx.getAmount();
        
        if(balance.compareTo(transferAmount)== -1) {
            Messager.showWarning("balanceKurang");
            hasil=false;
        }
            
        else if(transferAmount.compareTo(BigDecimal.valueOf(0)) < 1) {
            Messager.showWarning("balanceRequired");
            hasil=false;
        }
        
        else if(savtrx.getSaving().getSavaccntId().compareTo(savtrx.getDestSavaccntId())==0) {
            Messager.showWarning("accntSourceDestEqual");
            hasil=false;
        }
        
        if (hasil==true) hasil = cekConfig();
        
        return hasil;
    }
    
    public void trySave() {
        if (this.validate()) this.save();
    }
    
    private void validateLimit() {
        this.authorized = true;
                
        savtrx.setUserId(user.getUserId());
        Integer authorizedId = this.savHelper.authorized(savtrx.getSavtrxId());
        
        savtrx.setApprovalUid(authorizedId);
        
        //belum diotorisasi, cek validasi
        if (authorizedId == null) {
            BigDecimal ddAmount = savtrx.getAmount();
            BigDecimal ddAmountAlowed = user.getUgroup().getSavMaxTrx();
        
            if(ddAmount.compareTo(ddAmountAlowed) >= 0) this.authorized=false;
            
            //jika dlm rage limit, authorizedId = userId
            else savtrx.setApprovalUid(user.getUserId());
        }
        
        //men-triger history and balance
        savtrx.setPosted(authorized);
        
        if (authorized) savtrx.setPostedDate(new java.util.Date());
    }
    
    public void save() {
        validateLimit();
        
        //if (savtrx.getSavtrxId()==null)
            //savtrx.setTransferNo(newNumber());
        if (authorized==true) newNumber();
        
        boolean success = savHelper.saveData(savtrx);
                
        //this.editMode = (!success || !authorized);
        this.editMode = (!success);
                
        Messager.showSaveUpdateStatus(success);     
        
        if (!authorized && success)
            Messager.showWarning("unauthorized");    
        
        //ngahaja. biar inputBox bisa ngisi klo eror
        if (!success) authorized = true;
        else {
            
            //kalo sukses & athorized....
            if (authorized) authorized = false;
        }
        
        // re-insert
        if (!success && insertionMode) savtrx.setSavtrxId(null);
        else insertionMode = false;
        
        RequestContext.getCurrentInstance().addCallbackParam("success", success); 
    }

    public String getDefaultButton() {
        return defaultButton;
    }

    public void setDefaultButton(String defaultButton) {
        this.defaultButton = defaultButton;
    }
    
    public void handleCloseLookup(CloseEvent event) {
        this.showLookup=false;
    }
    
    public void handleCloseLookupDest(CloseEvent event) {
        this.showLookupDest=false;
    }
    
    private void ambilUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean logBean = (LoginBean) context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        this.user = logBean.getSelectedUser();
    }
}
